package com.cyandpos.pad.cateringformat.orderinfo;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.cyandpos.pad.R;
import com.cyandpos.pad.cateringformat.BaseFragment;
import com.cyandpos.pad.cateringformat.choosemenu.MenuFoodActivity;
import com.cyandpos.pad.cateringformat.orderinfo.adapter.OrderInfoAdapter;
import com.cyandpos.pad.cateringformat.orderinfo.adapter.OrderInfoItemAdapter;
import com.cyandpos.pad.common.commondata.ErpCommonData;
import com.cyandpos.pad.posdata.Goods;
import com.cyandpos.pad.posdata.Order;
import com.cyandpos.pad.posdata.QueryOrderReq;
import com.cyandpos.pad.posdata.RefundOrder;
import com.cyandpos.pad.posdata.TicketInfo;
import com.cyandpos.pad.sale.view.SelfNumKeyView;

import com.cyandpos.pad.tradedetails.view.TradeDetailsView;
import com.cyandpos.pad.tradedetails.presenter.TradeDetailsPresenter;
import com.cyandpos.pad.tradedetails.presenter.TradeDetailsPresenterImpl;
import com.cyandpos.pad.utils.CommonUtils;
import com.cyandpos.pad.utils.MoneyUtils;
import com.cyandpos.pad.utils.ToastUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static com.cyandpos.pad.utils.OrderType.ALLORDER;
import static com.cyandpos.pad.utils.OrderType.WFKORDER;
import static com.cyandpos.pad.utils.OrderType.YFKORDER;

/**
 * Created by xin on 2021/8/31
 * desc:
 */
public class OrderInfoFragment extends BaseFragment implements View.OnClickListener, TradeDetailsView {

    @BindView(R.id.fgbtn_order_info_sx)
    Button btn_order_info_sx; //刷新
    @BindView(R.id.btn_input_orderfood_no)
    Button btn_input_no;      //订单号
    @BindView(R.id.fg_orderfood_tablelist)
    ListView  tablelistview;  //订单列表
    @BindView(R.id.fg_orderfood_xqlist)
    ListView  orderfoodxqlist; //订单详情列表
    @BindView(R.id.fg_tv_order_hj)
    TextView textView_hj;      // 详情合计
    @BindView(R.id.fg_tv_order_yh)
    TextView textView_yh;      // 详情优惠


    @BindView(R.id.btn_addgoods)
    Button btnaddgoods;       //加菜
    @BindView(R.id.btn_order_cd)
    Button btnorder_cd;       //重打
    @BindView(R.id.btn_sumgoods)
    Button btnsumgoods;       //删菜
    @BindView(R.id.btn_order_gotopay)
    Button btnorder_gotopay; //去支付
    @BindView(R.id.switch_status)
    Spinner switchstatus; //去支付
    @BindView(R.id.tv_table_no)
    TextView tv_table_no;
    @BindView(R.id.tv_table_person)
    TextView tv_table_person;
    public static AlertDialog mDialog;//所有dialog
    private TradeDetailsPresenter mTradeDetailsPresenter;
    private QueryOrderReq orderReq;
    private ProgressDialog dialog;
    private List<Order> tempList=new ArrayList<Order>();
    public  int  selectPosition=-1;

    Unbinder unbinder;
    private OrderInfoItemAdapter infoItemAdapter;
    private OrderInfoAdapter orderInfoAdapter;
    private List<String> list_status;

    private boolean mIsDataInited;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_order_info_main, container, false);
        unbinder = ButterKnife.bind(this, view);
        if (!mIsDataInited) {
            if (getUserVisibleHint()) {
                initData();
                mIsDataInited = true;
            }
        }
        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        //防止数据预加载, 只预加载View，不预加载数据
        if (isVisibleToUser && isVisible() && !mIsDataInited) {
            initData();
            mIsDataInited = true;
        }
    }

    private void initData() {
        btn_order_info_sx.setOnClickListener(this);
        btn_input_no.setOnClickListener(this);
        btnaddgoods.setOnClickListener(this);
        btnorder_cd.setOnClickListener(this);
        btnsumgoods.setOnClickListener(this);
        btnorder_gotopay.setOnClickListener(this);

        mTradeDetailsPresenter = new TradeDetailsPresenterImpl(this);
        dialog = new ProgressDialog(getActivity());
        dialog.setCancelable(false);
        dialog.setMessage("正在查询明细，请稍等 ....");
        orderReq = new QueryOrderReq(); //添加默认 查询
        orderReq.setBeginTime(new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime())+" "+"00:00:00");
        orderReq.setEndTime(new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime())+" "+"23:59:59");
        orderReq.setSktno(ErpCommonData.sktno);
        orderReq.setQueryHistoryData(true);
        mTradeDetailsPresenter.QueryTradeDetails(orderReq);//默认今天
        orderInfoAdapter = new OrderInfoAdapter(getActivity(), tempList);
        tablelistview.setAdapter(orderInfoAdapter);
         tablelistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
             @Override
             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                  showgoodslist(tempList.get(position));
                  selectPosition=position;
             }
         });

        list_status = new ArrayList<>();
        list_status.add("已付款");
        list_status.add("未付款");
        list_status.add("全部");
        ArrayAdapter<String> adapter_kc_address = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, list_status);
        adapter_kc_address.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        switchstatus.setAdapter(adapter_kc_address);

    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(getActivity(),MenuFoodActivity.class);
        switch (v.getId()){
            case R.id.fgbtn_order_info_sx: //刷新
                orderReq = new QueryOrderReq(); //添加默认 查询
                orderReq.setBeginTime(new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime())+" "+"00:00:00");
                orderReq.setEndTime(new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime())+" "+"23:59:59");
                if (list_status.get(switchstatus.getSelectedItemPosition()).equals("已付款")){
                    orderReq.setStatus(YFKORDER);  // 1 是已付款
                }else if (list_status.get(switchstatus.getSelectedItemPosition()).equals("未付款")){
                    orderReq.setStatus(WFKORDER);  // 1 是未付款
                }else if (list_status.get(switchstatus.getSelectedItemPosition()).equals("全部")){
                    orderReq.setStatus(ALLORDER);  // 什么都不传 是查全部
                }
                orderReq.setSktno(ErpCommonData.sktno);
                orderReq.setQueryHistoryData(true);
                mTradeDetailsPresenter.QueryTradeDetails(orderReq);//默认今天
                break;
            case R.id.btn_input_orderfood_no: //订单查询
                //弹出键然后实行查询
                showInputorderoDialog(getActivity());

                break;
            case R.id.btn_addgoods:
                if (selectPosition<0){
                    Toast.makeText(getActivity(),"请选择单号",Toast.LENGTH_SHORT).show();
                    return;
                }
                TicketInfo ticketInfo= new TicketInfo();
                ticketInfo.setSubTickets(tempList.get(selectPosition).getSubTickets());
                ticketInfo.setOfferCouponList(tempList.get(selectPosition).getOfferCouponList());
                ticketInfo.setPayList(tempList.get(selectPosition).getPayList());
                ticketInfo.setLottoList(tempList.get(selectPosition).getLottoList());
                ticketInfo.setCasherInfo(tempList.get(selectPosition).getCasherInfo());
                ticketInfo.setMemberInfo(tempList.get(selectPosition).getMemberInfo());
                ticketInfo.setJlbh(tempList.get(selectPosition).getJlbh());
                ticketInfo.setOrderNo(tempList.get(selectPosition).getOrderNo());
                ticketInfo.setOrderTime(tempList.get(selectPosition).getOrderTime());
                ticketInfo.setTableNo(tempList.get(selectPosition).getTableId()+""); //桌号 lixin
                ticketInfo.setTablePerson(tempList.get(selectPosition).getMealsCount()+"");
                ErpCommonData.ticketInfo=ticketInfo;
                startActivity(intent);
                break;
            case R.id.btn_order_cd:
                ToastUtils.showMsg("重打开发中ing.....");
                break;
            case R.id.btn_sumgoods:
                if (selectPosition<0){
                    Toast.makeText(getActivity(),"请选择单号",Toast.LENGTH_SHORT).show();
                    return;
                }
                TicketInfo ticketInfo1= new TicketInfo();
                ticketInfo1.setSubTickets(tempList.get(selectPosition).getSubTickets());
                ticketInfo1.setOfferCouponList(tempList.get(selectPosition).getOfferCouponList());
                ticketInfo1.setPayList(tempList.get(selectPosition).getPayList());
                ticketInfo1.setLottoList(tempList.get(selectPosition).getLottoList());
                ticketInfo1.setCasherInfo(tempList.get(selectPosition).getCasherInfo());
                ticketInfo1.setMemberInfo(tempList.get(selectPosition).getMemberInfo());
                ticketInfo1.setJlbh(tempList.get(selectPosition).getJlbh());
                ticketInfo1.setOrderNo(tempList.get(selectPosition).getOrderNo());
                ticketInfo1.setOrderTime(tempList.get(selectPosition).getOrderTime());
                ticketInfo1.setTableNo(tempList.get(selectPosition).getTableId()+""); //桌号 lixin
                ticketInfo1.setTablePerson(tempList.get(selectPosition).getMealsCount()+"");
                ErpCommonData.ticketInfo=ticketInfo1;
                startActivity(intent);
                break;
            case R.id.btn_order_gotopay: {
                TicketInfo ticketInfo2 = new TicketInfo();
                ticketInfo2.setSubTickets(tempList.get(selectPosition).getSubTickets());
                ticketInfo2.setOfferCouponList(tempList.get(selectPosition).getOfferCouponList());
                ticketInfo2.setPayList(tempList.get(selectPosition).getPayList());
                ticketInfo2.setLottoList(tempList.get(selectPosition).getLottoList());
                ticketInfo2.setCasherInfo(tempList.get(selectPosition).getCasherInfo());
                ticketInfo2.setMemberInfo(tempList.get(selectPosition).getMemberInfo());
                ticketInfo2.setJlbh(tempList.get(selectPosition).getJlbh());
                ticketInfo2.setOrderNo(tempList.get(selectPosition).getOrderNo());
                ticketInfo2.setOrderTime(tempList.get(selectPosition).getOrderTime());
                ticketInfo2.setTableNo(tempList.get(selectPosition).getTableId()+""); //桌号 lixin
                ticketInfo2.setTablePerson(tempList.get(selectPosition).getMealsCount()+"");
                ErpCommonData.ticketInfo=ticketInfo2;
                startActivity(intent);

            }
            break;
            default:
                break;
        }

    }

    public void showInputorderoDialog(final Activity mContext) {
        final View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_queryorder, null);
        TextView tvName = view.findViewById(R.id.tv_dialog_title_name);
        final SelfNumKeyView sf_containt = view.findViewById(R.id.queryorder_keyboard);
        EditText order_query= view.findViewById(R.id.order_query_dialog);

        sf_containt.setEnterReceptor(order_query);
        sf_containt.setIsCanInputPoint(true);
        sf_containt.setOnCallBack(new SelfNumKeyView.SelfNumCallBack() {
            @Override
            public void keyBoardSure(String num,String hint) {
                if (CommonUtils.isNullOrEmpty(num)){
                    ToastUtils.showMsg("订单号不能为空");
                    return;
                }

                orderReq = new QueryOrderReq();
                orderReq.setSktno(ErpCommonData.sktno);
                orderReq.setOrderNo(num.toString());
                mTradeDetailsPresenter.QueryTradeDetails(orderReq);
            }
        });

        CommonUtils.setNoSoftware(order_query, getActivity(), true);

        tvName.setText("输入订单号查询");
        //关闭按钮
        tvName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();

            }
        });

        AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
        dialog.setView(view).setCancelable(false).create();
        mDialog = dialog.show();
    }

    @Override
    public void showProgress() {
        dialog.show();
    }
    @Override
    public void hideProgress() {
        dialog.dismiss();
    }

    @Override
    public void onTradeDetailsSuccess(List<Order> tradeDetailslist, double orderCount, RefundOrder data) {

        if (tradeDetailslist == null || tradeDetailslist.size() == 0) {
            ToastUtils.showMsg( "无销售信息");
            return;
        }

        tempList.clear();
        tempList.addAll(tradeDetailslist);
        orderInfoAdapter.notifyDataSetChanged();
        int  totlemoney=0;
        for (int i=0;i<tradeDetailslist.size();i++){
            totlemoney+=tradeDetailslist.get(i).getTotalMoneyOut();
        }
    }

    private void showgoodslist(Order order) {
        tv_table_no.setText("餐桌号："+order.getTableId());
        tv_table_person.setText("就餐人数："+order.getMealsCount());
        if (order.getSubTickets().size()>0){
            infoItemAdapter = new OrderInfoItemAdapter(getActivity(), order.getSubTickets().get(0).getGoodsList());
            orderfoodxqlist.setAdapter(infoItemAdapter);
            infoItemAdapter.notifyDataSetChanged();
            textView_hj.setText("合计："+ MoneyUtils.getMoneyStr(order.getSubTickets().get(0).getTotalMoney()));
            textView_yh.setText("优惠："+ MoneyUtils.getMoneyStr(order.getSubTickets().get(0).getTotalDiscount()));
        }else {
            List<Goods>  goods= new ArrayList<>();  //更新空数据
            infoItemAdapter = new OrderInfoItemAdapter(getActivity(), goods);
            orderfoodxqlist.setAdapter(infoItemAdapter);
            textView_hj.setText("合计："+0.00);
            textView_yh.setText("优惠："+ 0.00);
        }
    }

    @Override
    public void showLoadFailMsg(String errorMsg) {
        tempList.clear();
        orderInfoAdapter.notifyDataSetChanged();
        Toast.makeText(getActivity(), "查询订单信息失败 " + errorMsg, Toast.LENGTH_LONG).show();
    }
}
